package com.hopscotch.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hopscotch.entity.*;
import com.hopscotch.service.UserService;
import com.hopscotch.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;


@RestController
@RequestMapping("/user")
@CrossOrigin
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public R userLogin(@RequestBody UserLoginVO userLoginVO, HttpSession session){

        User user = userService.userLogin(userLoginVO);
        if (user != null){
            session.setAttribute("user",user.getUsername());
            return R.success(user);
        }else {
            return R.fail();
        }
    }

    @GetMapping("/outlogin")
    public R userOutLogin(HttpSession session){
        session.invalidate();
        return R.success(null);
    }

    @GetMapping("/search")
    public R userGet(UserGetVO userGetVO){
        //log.debug("userGetVO的createTime值为{}", Arrays.toString(userGetVO.getCreateTime()));
        PageHelper.startPage(userGetVO.getPageNum(), userGetVO.getPageSize());
        UserGetDTO userGetDTO = new UserGetDTO(userGetVO);
        List<User> user = userService.userGet(userGetDTO);
        PageInfo<User> pageInfo = new PageInfo<>(user);
        //log.debug(String.valueOf(pageInfo));
        UserListVO userListVO = new UserListVO(user, pageInfo);
        return R.success(userListVO);
    }

    @GetMapping("/delete")
    public R userDelete(@RequestParam List<String> idList){
        userService.userDelete(idList);
        return R.success(null);
    }

    @PostMapping("/insert")
    public R userInsert(@RequestBody UserInsertOrUpdateVO userInsertOrUpdateVO){
        userService.userInsert(userInsertOrUpdateVO);
        return R.success(null);
    }

    @PostMapping("/update")
    public R userUpdate(@RequestBody UserInsertOrUpdateVO userInsertOrUpdateVO){
        userService.userUpdate(userInsertOrUpdateVO);
        return R.success(null);
    }
}
